﻿using Configuration;
using PLC.Base;
using PLC.Device;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PLC.Manager
{
    public class EnvDataManager: IEnvDataManager
    {
        IDeviceReader plcManager;
        IDeviceReader serialManager;


        #region 对外接口
        /// <summary>
        /// 初始化读取组件
        /// </summary>
        public void Init()
        {
            plcManager = new PLCSmart200Manager(PLCConfig.IP, PLCConfig.Rack, PLCConfig.Slot, PLCConfig.ConnectionType);
            serialManager = new ModBusRTUManager(ModBusConfig.PortName, ModBusConfig.BaudRate, ModBusConfig.Parity, ModBusConfig.DataBits, ModBusConfig.StopBits, ModBusConfig.ReadTimeOut);
        }

        /// <summary>
        /// 初始化读取组件
        /// </summary>
        public void init_hl()
        {
            plcManager = new PLCSmart200Manager(PLCConfig.IP, PLCConfig.Rack, PLCConfig.Slot, PLCConfig.ConnectionType);
            serialManager = new SerialPortManager(SerialPortConfig.Port, SerialPortConfig.BaudRate, SerialPortConfig.Parity, SerialPortConfig.DataBits, SerialPortConfig.StopBits);
        }

        public int Open()
        {
            int ret1, ret2 = 0;
            ret1 = plcManager.Open();
            ret2 = serialManager.Open();

            if (ret1 != 0)
            {
                throw new Exception("打开PLC异常！");
            }
            if (ret2 != 0)
            {
                throw new Exception("打开串口异常！");
            }
            return 0;
        }

        public void Close()
        {
            plcManager.Close();
            serialManager.Close();
        }

        /// <summary>
        /// 流量计，电流变比和电箱读取的相数地址是可变的，并且不可配置，需要每次读的时候输入
        /// </summary>
        /// <param name="dn"></param>
        /// <param name="transformRadio"></param>
        /// <param name="phaseAdrees"></param>
        /// <returns></returns>
        public EnvData ReadData(DynamicParams dynamicParams)
        {
            EnvData plcEnvData = plcManager.ReadData(dynamicParams);
            EnvData serialsEnvData = serialManager.ReadData(dynamicParams);
           

            EnvData data = new EnvData();
            data.Current = serialsEnvData.Current;
            data.Voltage = serialsEnvData.Voltage;
            data.ShaftPower = serialsEnvData.ShaftPower;

            data.Flow = plcEnvData.Flow;
            data.PresureIn = plcEnvData.PresureIn;
            data.PresureOut = plcEnvData.PresureOut;
            data.Flow = plcEnvData.Flow;

            data.Temperature = plcEnvData.Temperature;
            data.Speed = plcEnvData.Speed;
            data.TransRadio = plcEnvData.TransRadio;
            
            return data;
        }

        public void FetchData()
        {
            //throw new NotImplementedException();
        }

        #endregion
    }
}
